package com.yunhai.support.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyun.sdk.service.dysmsapi20170525.AsyncClient;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yunhai.common.dto.GlobalException;
import com.yunhai.common.dto.PaginationVo;
import com.yunhai.support.entity.PhoneTextMessage;
import com.yunhai.support.entity.vo.TextMessageVo;
import com.yunhai.support.mapper.AliMessageMapper;
import com.yunhai.support.service.AliMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
public class AliMessageServiceImpl implements AliMessageService {

    private static String TEMPLATE_CODE = "SMS_180345533";
    private static String SIGN_NAME = "天镜云网络科技";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    private AsyncClient aliMessageClient;
    @Resource
    private AliMessageMapper aliMessageMapper;

    /**
     * 手机验证码短信，用于账号注册，登录等
     */
    @Transactional
    public void sendAlarmInfo(String phone,
                              String serialNumber,
                              String nickName,
                              String strength,
                              String energy,
                              Integer bal) throws Exception {


        Map map = new HashMap();
        map.put("name", nickName);
        map.put("serial", serialNumber);
        map.put("Strength", strength);
        map.put("Energy", energy);
        map.put("bal", (bal / 100.0));
        String content = JSON.toJSONString(map);

        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(SIGN_NAME)
                .templateCode(TEMPLATE_CODE)
                .phoneNumbers(phone)
                .templateParam(content)
                .build();

        //发送内容
        CompletableFuture<SendSmsResponse> response = aliMessageClient.sendSms(sendSmsRequest);
        //获取发送内容
        SendSmsResponse resp = response.get();
        SendSmsResponseBody body = resp.getBody();
        /**
         * 内容发送成功之后，将发送数据记录到数据库中。
         * */
        PhoneTextMessage phoneTextMessage = new PhoneTextMessage();
        phoneTextMessage.setSerialNumber(serialNumber)
                .setPhone(phone)
                .setContent(content)
                .setSendStatus(1)
                .setDelFlag(0);

        //短信发送成功
        boolean isSuccess = "OK".equals(body.getCode());
        if (isSuccess) {
            phoneTextMessage.setSendStatus(0);
        } else {
            phoneTextMessage.setSendStatus(1);
            phoneTextMessage.setReason(body.getMessage());
        }
        //将发送的内容
        aliMessageMapper.insert(phoneTextMessage);
        //这里需要判断短信是否发送成功。如果成功，
        log.info("sendPhoneCode: ");
        log.info(new Gson().toJson(resp));

        if (!isSuccess) {
            throw GlobalException.gen(10018, body.getMessage());
        }
    }


    /**
     * 发送来电、停电的短信
     */
    @Transactional
    public void sendElectricAlarmInfo(String phone,
                              String serialNumber,
                              String nickName,
                              Integer type,
                              Integer bal) throws Exception {


        Map map = new HashMap();
        map.put("name", nickName);
        map.put("imei", serialNumber);
        map.put("balance", (bal / 100.0));
        map.put("time",  simpleDateFormat.format(new Date()));
        String content = JSON.toJSONString(map);

        String  templateCode = "";
        //表示来电
        if( type == 1 ){
            templateCode = "SMS_466235019";
        }else {
            templateCode = "SMS_466200028";
        }
        SendSmsRequest sendSmsRequest = SendSmsRequest.builder()
                .signName(SIGN_NAME)
                .templateCode(templateCode)
                .phoneNumbers(phone)
                .templateParam(content)
                .build();

        //发送内容
        CompletableFuture<SendSmsResponse> response = aliMessageClient.sendSms(sendSmsRequest);
        //获取发送内容
        SendSmsResponse resp = response.get();
        SendSmsResponseBody body = resp.getBody();
        /**
         * 内容发送成功之后，将发送数据记录到数据库中。
         * */
        PhoneTextMessage phoneTextMessage = new PhoneTextMessage();
        phoneTextMessage.setSerialNumber(serialNumber)
                .setPhone(phone)
                .setContent(content)
                .setSendStatus(1)
                .setDelFlag(0);

        //短信发送成功
        boolean isSuccess = "OK".equals(body.getCode());
        if (isSuccess) {
            phoneTextMessage.setSendStatus(0);
        } else {
            phoneTextMessage.setSendStatus(1);
            phoneTextMessage.setReason(body.getMessage());
        }
        //将发送的内容
        aliMessageMapper.insert(phoneTextMessage);
        //这里需要判断短信是否发送成功。如果成功，
        log.info("sendPhoneCode: ");
        log.info(new Gson().toJson(resp));

        if (!isSuccess) {
            throw GlobalException.gen(10018, body.getMessage());
        }
    }


    @Override
    public IPage getTextMessagePagination(PaginationVo paginationVo, TextMessageVo textMessageVo) throws Exception {

        LambdaQueryWrapper<PhoneTextMessage> lqs = new LambdaQueryWrapper<>();
        lqs.eq(textMessageVo.getSerialNumber() != null, PhoneTextMessage::getSerialNumber, textMessageVo.getSerialNumber());
        lqs.eq(textMessageVo.getPhoneNumber() != null, PhoneTextMessage::getPhone, textMessageVo.getPhoneNumber());
        lqs.ge(textMessageVo.getCreateStartTime() != null, PhoneTextMessage::getCreateTime, textMessageVo.getCreateStartTime());
        lqs.le(textMessageVo.getCreateEndTime() != null, PhoneTextMessage::getCreateTime, textMessageVo.getCreateEndTime());
        IPage page = new Page(paginationVo.getPageIndex(), paginationVo.getPageSize());
        aliMessageMapper.selectPage(page, lqs);
        return page;
    }

    @Override
    public List<PhoneTextMessage> getTextMessageList() throws Exception {

        List<PhoneTextMessage> phoneTextMessages = aliMessageMapper.selectList(null);
        return phoneTextMessages;
    }
}
